<style lang="stylus">
@import "../style/film.styl"
.search-page
  min-height 100%
  overflow hidden
  padding-top 158px
  .top-header
    box-sizing border-box
    padding-top 70px
    height 158px
    background url("../assets/index/index_header_03.jpg") no-repeat
    background-size cover
    position fixed
    top 0
    width 100%
    z-index 3
    max-width 750px;/*no*/
    margin 0 auto
  .search-icon
    width 60px
    height 37px
    background url("../assets/search/icon_search.png") no-repeat left center
    background-size 37px 100%
  .delete-icon
    width 30px
    height 30px
    background url("../assets/search/icon_close.png") no-repeat right center
    background-size 30px
  input
    background transparent
    border 0
    height 36px
    &::-webkit-input-placeholder
      font-size 28px
      color #afabd2
  .border-btm
    border-bottom 2px solid #fff
    padding-bottom 8px
  .clear-history
    height 34px
    line-height 34px
    background url("../assets/search/icon_delete.png") no-repeat right top
    background-size 28px 34px
  .history
    background #f5f5f5
    border-radius 4px
    & + .history
      margin-left 12px
  .histories
    max-height 138px
    overflow hidden
  .rank-title
    min-width 80px
    text-align left
    & + .rank-title
      margin-left 46px
  .rank-item
    height 80px
  .rank-no
    width 28px
    line-height 28px
    border-radius 6px
    border 3px solid #999
    &.third
      color #e49d37
      border-color #e49d37
    &.second
      color #e46c37
      border-color #e46c37
    &.first
      color #cf4f4c
      border-color #cf4f4c
  .film-trend
    background-color #a0a0a0
    width 11px
    height 3px
    &.down
      width 12px
      height 14px
      background url("../assets/search/icon_down.png")
      background-size cover
    &.up
      width 12px
      height 14px
      background url("../assets/search/icon_up.png")
      background-size cover
  .see-recommend
    background-color #5142be
    border-radius 6px
    line-height 80px
</style>
<template lang="pug">
.search-page
  .top-header.pdl-30.pdr-20.flex
    .flex.flex-1.border-btm
      .search-icon
      input.fz-30.flex-1.white(ref="searchInput" v-model="keywords", @change="onSearch", @keyup.enter="onSearch(1)", @input="onInput", @focus="onFocus", @blur="onBlur", :placeholder="hotKeyword ? '大家都在搜“' + hotKeyword + '”' : '输入您想找的影片名称'")
      .delete-icon.pdl-30(@click="clearKeywords")
    .white.pdl-48(@click="onBack") 取消
  template(v-if="keywords && loadDone && (!items.length || !items.filter(ele => ele.isAd != true).length)")
    .empty-data
    .fz-22.gray-99.center.mgt-20 没有找到您搜索的影片
    .see-recommend.mg-52.white.fz-36.center(@click="onGoHome") 查看精选推荐影片
  template(v-if="(!keywords || entering) && !items.length")
    .pdh-20.pdt-38.pdb-42.bdb(v-if="histories.length > 0")
      .flex
        .bold 历史搜索
        .flex-1
        .fz-22.clear-history.pdr-36(@click="clearHistory") 清空
      .flex.flex-wrap.mgt-16.histories
        .history.mgt-12.pdh-26.pdv-12.fz-22(v-for="(history, index) in histories", :key="index", @click="onKeywordsSearch(history)") {{history | truncate(9)}}
    .mgt-52.flex.pdh-30.flex-scrollable
      .rank-title(v-for="(rank, index) in ranks", :key="index", :class="index === rankNum ? 'bold': ''", @click="onSelectRank(index)") {{rank.title}}
    .rank-list.mgt-30(v-if="ranks.length")
      .rank-item.pdl-30.flex.pdr-34(v-for="(item, index) in ranks[rankNum].data", :key="index", @click="onItemDispatch(item)")
        .rank-no.fz-14.center.bold(:class="{first:index===0,second:index===1,third:index===2}") {{index + 1}}
        .title.fz-26.mgl-22 {{item.title}}
        .film-tag.mgl-34(v-if="item.data.recmdTag > 0", :class="VIDEO_LABEL[item.data.recmdTag]")
        .flex-1
        .film-trend(:class="{up: item.trend === 1,down: item.trend === 2}")
  template(v-else)
    search-item(v-for="(item, index) in items", :key="index", :item="item", :class="{'pdt-30': index === 0}")
  .loading-more.center.fz-30.pdv-20(v-show="showMoreLoading") 加载中...
  no-more(v-if="!hasMore && items.length")
</template>

<script>
import SearchItem from '../components/SearchItem.vue'
import paging from '../mixin/paging'

import { VIDEO_LABEL, CACHE_KEY } from '../const'

const MAX_HISTORY_COUNT = 15 // 最多保存的history的条数

export default {
  name: 'search',
  components: { SearchItem },
  mixins: [paging],
  data() {
    return {
      keywords: '',
      histories: [],
      entering: false,
      ranks: [],
      rankNum: 0,
      VIDEO_LABEL,
      hotKeyword: '',
      hotKeywords: [],
      hotKeywordIndex: 0,
      hotKeywordTimer: null
    }
  },

  mounted() {
    this.histories = this.getStore(CACHE_KEY.SEARCH_HISTORY) || []
    this.$get('movie/search/hot').then(ranks => {
      this.ranks = ranks
    })

    this.hotKeywords = this.getStore(CACHE_KEY.HOT_KEYWORDS) || []
    this.checkHotKeyword()
  },

  computed: {
    paging() {
      if (!this.keywords) {
        return
      }

      return {
        path: 'movie/search',
        params: {
          keyword: this.keywords
        }
      }
    }
  },

  methods: {
    checkHotKeyword() {
      if (this.hotKeywords && this.hotKeywords.length > 0) {
        this.hotKeyword = this.hotKeywords[this.hotKeywordIndex++].keyword
        if (this.hotKeywordIndex >= this.hotKeywords.length) {
          this.hotKeywordIndex = 0
        }
        this.hotKeywordTimer = setTimeout(this.checkHotKeyword.bind(this), 2000)
      }
    },

    onSelectRank(index) {
      this.rankNum = index
    },

    clearKeywords() {
      this.keywords = ''
      this.loadDone = false
      this.items = []
      this.checkHotKeyword()
    },

    clearHistory() {
      this.histories = []
      this.clearStore(CACHE_KEY.SEARCH_HISTORY)
    },

    onFocus() {
      this.entering = true
      this.clearTimer()
      if (this.hotKeywords.length) {
        this.keywords = this.hotKeyword
      }
    },

    clearTimer() {
      if (this.hotKeywordTimer) {
        this.hotKeywordTimer = null
        clearTimeout(this.hotKeywordTimer)
      }
    },

    onBlur() {
      this.entering = false
      if (this.keywords.trim().length === 0) {
        this.checkHotKeyword()
      }
    },

    onInput() {
      this.entering = true
      if (this.keywords.trim().length === 0) {
        this.loadDone = false
        this.items = []
        this.checkHotKeyword()
      }
    },

    onKeywordsSearch(keywords) {
      this.clearTimer()
      this.keywords = keywords
      this.fetch()
    },

    onSearch(type) {
      if (type == 1) {
        this.$refs.searchInput.blur();
      }
      this.entering = false
      if (this.keywords.trim().length) {
        // 防止重复添加
        if (this.histories.indexOf(this.keywords.trim()) === -1) {
          this.histories.unshift(this.keywords.trim())
        }

        // 超过就清理掉后面的数据
        if (this.histories.length > MAX_HISTORY_COUNT) {
          this.histories.pop()
        }

        this.saveStore(CACHE_KEY.SEARCH_HISTORY, this.histories)

        if (this.config.env.isApp) {
          this.action('log', {
            event: 'search_movie',
            params: {
              userId: this.userId || 0,
              keyword: this.keywords.trim()
            }
          })
        }
        this.fetch()
      }
    },
    onGoHome() {
      if (this.config.env.isBrowser) {
        this.onLinkPage('/home')
      } else {
        this.action('home')
      }
    },
  }
}
</script>
